#!/usr/bin/env python
#

from google.appengine.ext import db
from google.appengine.ext import blobstore

class ImageUrlMap(db.Model):
    # try to use GetBlobstoreKey() below instead of blobstoreinfo.Key()
    blobstoreinfo = blobstore.BlobReferenceProperty(required=True)
    datecreated = db.DateTimeProperty(required=True, auto_now_add=True)
    imgserving_url = db.URLProperty()
    # we keep the other 2 pieces of information so we don't have to load
    # the blob_info all the time. also, if we copy this table to
    # difference service, the blob_info isn't copied.
    filename = db.StringProperty(required=True)
    filesize = db.IntegerProperty(required=True)
    batchid = db.IntegerProperty(required=True, default=0)
    # other data you could keep here: userid


    # if you call blobstoreinfo.key(), you'll make a 2nd call to the database
    # to load the blobstore record.
    # Use this call to get the key without loading the data
    def GetBlobstoreKey(self):
        return ImageUrlMap.blobstoreinfo.get_value_for_datastore(self)

    @staticmethod
    def GetbyIdAndFilename(idstr, filename):
        map = ImageUrlMap.get_by_id(int(idstr))
        if not map:
            return None
        # we use the filename to enforce uniqueness
        # (e.g. user can't pick an id and get back a file, they most know both)
        if map.filename != filename:
            logging.info('id found, but filename mismatch "%s" vs "%s" ')
            return None
        return map

    def DeepDelete(self):
        # first delete the blobstore associated with this info
        # NOTE: there is no api to delete an image from the PIS, it lives on
        # until that service runs some kind of cleanup job.
        # Docs say "This takes up to 24 hours to take effect."
        self.blobstoreinfo.delete()
        self.delete()

